package cn.levill.domain.strategy.service.rule.chain.impl;

import cn.levill.domain.strategy.repository.IStrategyRepository;
import cn.levill.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.levill.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.levill.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Levill
 * @description 黑名单逻辑链
 * @date 2025/02/03 21:31
 */
@Slf4j
@Component("rule_blacklist")
public class BlackListLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("规则过滤-黑名单 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());

        // 查询黑名单规则具体值
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());

        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        // 取出黑名单固定返回的奖品Id
        Integer awardId = Integer.parseInt(splitRuleValue[0]);

        // 100:user001,user002,user003
        // 黑名单用户Id
        String[] userBlackIds = splitRuleValue[1].split(Constants.SPLIT);

        for (String userBlackId : userBlackIds) {
            // 判断userId是否与userBlackId相同
            if (userId.equals(userBlackId)) {
                log.info("抽奖责任链-黑名单接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
                return DefaultChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModel())
                        .build();
            }
        }

        // 过滤其他责任链
        log.info("抽奖责任链-黑名单放行 userId:{} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        return next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }
}
